package com.jack.leetcode.eachproblem_2020;

public class 删除链表的第N个节点 {

    public class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode prev = new ListNode(-1);
        prev.next = head;
        ListNode left = head;
        ListNode right = head;
        while((n--) != 0){
            right = right.next;
        }
        while(right != null){
            prev = prev.next;
            left = left.next;
            right = right.next;
        }
        if(prev.next == head){
            return head.next;
        }
        prev.next = left.next;
        return head;
    }
}
